package com.ghao.douban.services.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ghao.douban.Entity.MovieInfo;
import com.ghao.douban.mapper.MovieInfoMapper;
import com.ghao.douban.services.MovieInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Ghao
 * @date 2021/7/20 10:23
 */
@Service
public class MovieInfoServiceImpl implements MovieInfoService {

    @Autowired
    private MovieInfoMapper movieInfoMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String DOUBAN_REDIS_KEY = "stealPage";

    private static final String DOUBAN_MOVIE_INFO_URL_PREFIX = "https://movie.douban.com/j/search_subjects";

    private static final String DOUBAN_URL_TAG_HOT = "热门";

    private static final String DOUBAN_URL_TYPE_MOVIE = "movie";

    private static final int DOUBAN_PAGE_SIZE = 20;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 每10s向豆瓣请求50条数据
     * @author Ghao
     * @date 2021/7/20 15:0
     */
    @Override
    public void getMovieFromDouban() {
        //设置url请求参数
        Map<String, Object> map = httpParam();
        //拼接url
        String jsonResponse = HttpUtil.get(DOUBAN_MOVIE_INFO_URL_PREFIX, map);
        //切分url
        JSONObject jsonObject = JSONUtil.parseObj(jsonResponse);
        logger.info(jsonResponse);
        JSONArray array = jsonObject.getJSONArray("subjects");
        //遍历JSONArray拿到对象
        //如果结果是空的就回滚一次
        if (array.size() == 0){
            int pageStart = Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get(DOUBAN_REDIS_KEY))) + DOUBAN_PAGE_SIZE;
            stringRedisTemplate.opsForValue().set(DOUBAN_REDIS_KEY, (pageStart -  2 * DOUBAN_PAGE_SIZE) + "");
        }else {
            for (Object o : array) {
                MovieInfo movieInfo = JSONUtil.toBean((JSONObject) o, MovieInfo.class);
                movieInfoMapper.insert(movieInfo);
            }
        }

    }

    @Override
    public List<MovieInfo> selectMovieByPage(Page<MovieInfo> page) {
        LambdaQueryWrapper<MovieInfo> wrapper = new LambdaQueryWrapper<>();

        return movieInfoMapper.selectPage(page, wrapper).getRecords();
    }

    /**
      * 配置url请求的参数
      * @author Ghao
      * @date 2021/7/20 15:15
      * @return map格式的请求参数
      */
    private Map<String, Object> httpParam() {
        //从redis中拿到当前的页数
        int pageStart = Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get(DOUBAN_REDIS_KEY))) + DOUBAN_PAGE_SIZE;
        logger.info("页数：" + pageStart);
        //页数加size
        stringRedisTemplate.opsForValue().set(DOUBAN_REDIS_KEY, pageStart + "");
        HashMap<String, Object> paramMap = new HashMap<>(8);
        paramMap.put("type", DOUBAN_URL_TYPE_MOVIE);
        paramMap.put("tag", DOUBAN_URL_TAG_HOT);
        paramMap.put("page_limit", DOUBAN_PAGE_SIZE);
        paramMap.put("page_start", pageStart);
        return paramMap;
    }

}
